package com.hmall.order.web;

import cn.hutool.core.bean.BeanUtil;
import com.hmall.common.client.AddressClient;
import com.hmall.common.client.ItemClient;
import com.hmall.common.pojo.Address;
import com.hmall.common.pojo.Item;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.pojo.OrderRequest;
import com.hmall.order.service.IOrderDetailService;
import com.hmall.order.service.IOrderLogisticsService;
import com.hmall.order.service.IOrderService;
import com.hmall.order.utils.MyThreadLoacl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@RequestMapping("order")
public class OrderController {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IOrderDetailService orderDetailService;

    @Autowired
    private IOrderLogisticsService orderLogisticsService;

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private AddressClient addressClient;


    @GetMapping("{id}")
    public Order queryOrderById(@PathVariable("id") Long orderId) {
        return orderService.getById(orderId);
    }


    /**
     * 创建订单
     *
     * @param request
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping()
    public Long addOrder(@RequestBody OrderRequest request) {
        //根据itemId查询商品
        Item item = itemClient.getById(request.getItemId());
        //基于商品价格、购买数量计算商品总价：totalFee
        Long totalFee =Long.valueOf(item.getPrice() * request.getNum()) ;
        //封装Order对象，初识status为未支付
        String userId = MyThreadLoacl.getSubject();
        Order order = Order.builder().totalFee(totalFee)
                .paymentType(3)
                .userId(Long.valueOf(userId))
                .status(1)
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .closeTime(LocalDateTime.now().plusMinutes(30))
                .build();
        //将Order写入数据库tb_order表中
        orderService.save(order);
        //将商品信息、orderId信息封装为OrderDetail对象，写入tb_order_detail表
        OrderDetail orderDetail = OrderDetail.builder().orderId(order.getId())
                .itemId(item.getId())
                .num(request.getNum())
                .title(item.getName())
                .spec(item.getSpec())
                .price(item.getPrice())
                .image(item.getImage())
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .build();
        orderDetailService.save(orderDetail);
        //将user - service的根据id查询地址接口封装为FeignClient
        //根据addressId查询user - service服务，获取地址信息
        Address address = addressClient.findAddressById(request.getAddressId());
        //将地址封装为OrderLogistics对象，写入tb_order_logistics表
        OrderLogistics orderLogistics = BeanUtil.toBean(address, OrderLogistics.class);
        orderLogistics.setOrderId(order.getId());
        orderLogistics.setContact(address.getContact());
        orderLogistics.setPhone(address.getMobile());
        orderLogisticsService.save(orderLogistics);
        //在item - service提供减库存接口，并编写FeignClient
        //调用item - service的减库存接口
        itemClient.stockNum(item.getId(), request.getNum());
        return order.getId();
    }
}
